package stub;

import com.google.gdata.client.GDataProtocol.Query;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.DateSelectEvent;
import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.ScheduleEntrySelectEvent;
import org.primefaces.model.*;

@ManagedBean
@SessionScoped
public class ScheduleController {

    private ScheduleModel eventModel;
    private ScheduleModel lazyEventModel;
    private ScheduleEvent event = new DefaultScheduleEvent();
    private CalendarService client = new CalendarService("yourCo-yourAppName-v1");

    public ScheduleController() throws Exception {
        client.setUserCredentials("13623650117@163.com", "March25th");

        eventModel = new DefaultScheduleModel();

        URL feedUrl = new URL("https://www.google.com/calendar/feeds/13623650117@163.com/private/full");
        CalendarEventFeed myFeed = client.getFeed(feedUrl, CalendarEventFeed.class);
        for (int i = 0; i != myFeed.getEntries().size(); i++) {
            eventModel.addEvent(new DefaultScheduleEvent(myFeed.getEntries().get(i).getTitle().getPlainText(), new Date(myFeed.getEntries().get(i).getTimes().get(0).getStartTime().getValue()), new Date(myFeed.getEntries().get(i).getTimes().get(0).getEndTime().getValue())));
        }

        ((DefaultScheduleEvent) event).setTitle("");

        lazyEventModel = new LazyScheduleModel() {

            @Override
            public void loadEvents(Date start, Date end) {
                clear();

                Date random = getRandomDate(start);
                addEvent(new DefaultScheduleEvent("Lazy Event 1", random, random));

                random = getRandomDate(start);
                addEvent(new DefaultScheduleEvent("Lazy Event 2", random, random));
            }
        };
    }

    public Date getRandomDate(Date base) {
        Calendar date = Calendar.getInstance();
        date.setTime(base);
        date.add(Calendar.DATE, ((int) (Math.random() * 30)) + 1);        //set random day of month

        return date.getTime();
    }

    public Date getInitialDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);

        return calendar.getTime();
    }

    public ScheduleModel getEventModel() {
        return eventModel;
    }

    public ScheduleModel getLazyEventModel() {
        return lazyEventModel;
    }

    public ScheduleEvent getEvent() {
        return event;
    }

    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }

    public void addEvent(ActionEvent actionEvent) throws Exception {
        if (event.getId() == null) {
            eventModel.addEvent(event);

            URL postUrl = new URL(
                    "https://www.google.com/calendar/feeds/13623650117@163.com/private/full");
            CalendarEventEntry myEntry = new CalendarEventEntry();

            myEntry.setTitle(new PlainTextConstruct(((DefaultScheduleEvent) event).getTitle()));

            DateTime startTime = new DateTime(((DefaultScheduleEvent) event).getStartDate());
            DateTime endTime = new DateTime(((DefaultScheduleEvent) event).getEndDate());
            When eventTimes = new When();
            eventTimes.setStartTime(startTime);
            eventTimes.setEndTime(endTime);
            myEntry.addTime(eventTimes);
            client.insert(postUrl, myEntry);

        } else {
            eventModel.updateEvent(event);
        }

        event = new DefaultScheduleEvent();
        ((DefaultScheduleEvent) event).setTitle("");
    }

    public void deleteEvent(ActionEvent actionEvent) throws Exception {
        if (event.getId() == null) {
            
        } else {
            eventModel.deleteEvent(event);

            URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
            CalendarQuery myQuery = new CalendarQuery(feedUrl);
            myQuery.setFullTextQuery(event.getTitle());
            CalendarEventFeed myResultsFeed = client.query(myQuery,
                    CalendarEventFeed.class);
            if (myResultsFeed.getEntries().size() > 0) {
                CalendarEventEntry firstMatchEntry = (CalendarEventEntry) myResultsFeed.getEntries().get(0);
                firstMatchEntry.delete();
            }
            
            eventModel.updateEvent(event);
        }

        event = new DefaultScheduleEvent();
        ((DefaultScheduleEvent) event).setTitle("");
    }
    
    public void onEventSelect(ScheduleEntrySelectEvent selectEvent) {
        event = selectEvent.getScheduleEvent();
    }

    public void onDateSelect(DateSelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", selectEvent.getDate(), selectEvent.getDate());
    }

    public void onEventMove(ScheduleEntryMoveEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

        addMessage(message);
    }

    public void onEventResize(ScheduleEntryResizeEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());

        addMessage(message);
    }

    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
}